package com.neusoft.neuiotms.dcam.fixed.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.bizcore.web.dto.result.PageResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.fixed.dto.GoodsFileDTO;
import com.neusoft.neuiotms.dcam.fixed.service.GoodsFileService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "货品档案管理")
@RestController
@RequestMapping(value = "/api/w/fixed/goodsFile")
public class GoodsFileController {

    @Autowired
    private GoodsFileService goodsFileService;

    @ApiOperation("查询所有货品档案")
    @GetMapping
    public ResultListDTO<GoodsFileDTO> index() {
        final List<GoodsFileDTO> goodsFileDTOs = this.goodsFileService.findAll();
        return ResultListDTO.success(goodsFileDTOs);
    }

    @ApiOperation("查询指定备品备件类型的货品档案")
    @GetMapping("/spt/{code}")
    public ResultListDTO<GoodsFileDTO> listBySpareTypeCode(@PathVariable final String code) {
        final List<GoodsFileDTO> goodsFileDTOs = this.goodsFileService.listBySpareTypeCode(code);
        return ResultListDTO.success(goodsFileDTOs);
    }

    @ApiOperation("创建货品档案")
    @PostMapping
    public ResultDTO<GoodsFileDTO> create(@RequestBody final GoodsFileDTO dto) {
        final GoodsFileDTO result = this.goodsFileService.create(dto);
        return ResultDTO.success(result);
    }

    @ApiOperation("货品档案详情")
    @GetMapping("/{id}")
    public ResultDTO<GoodsFileDTO> details(@PathVariable final Long id) {
        final GoodsFileDTO dto = this.goodsFileService.details(id);
        return ResultDTO.success(dto);
    }

    @ApiOperation("删除固定资产产品")
    @DeleteMapping("/{id}")
    public ResultDTO<Void> delete(@PathVariable final Long id) {
        this.goodsFileService.delete(id);
        return ResultDTO.success();
    }

    @ApiOperation("修改货品档案")
    @PutMapping("/{id}")
    public ResultDTO<GoodsFileDTO> update(@PathVariable final Long id,
            @RequestBody final GoodsFileDTO dto) {
        final GoodsFileDTO result = this.goodsFileService.update(id, dto);
        return ResultDTO.success(result);
    }

    @ApiOperation("分页查询所有货品档案")
    @GetMapping("/p")
    public PageResultDTO<GoodsFileDTO> search(final Pageable pageable, final Searchable searchable) {
        return PageResultDTO.success(this.goodsFileService.search(pageable, searchable));
    }

    @ApiOperation("下载模板")
    @GetMapping("/template")
    public void template(final HttpServletResponse response) {
        final Workbook workbook = this.goodsFileService.template();
        if (workbook == null) {
            GoodsFileController.log.error("模板导出失败");
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("货品导入模板" + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            GoodsFileController.log.error("下载模板失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                GoodsFileController.log.error("下载模板关闭输出流失败", e);
            }
        }
    }

    @ApiOperation("导入货品")
    @PostMapping("/import")
    public ResultDTO<?> upload(@RequestParam("file") final MultipartFile file) {
        final String msg = this.goodsFileService.upload(file);
        if (!StringUtils.isEmpty(msg)) {
            return ResultDTO.failure(msg);
        }
        return ResultDTO.success(msg);
    }

    @ApiOperation("导出货品")
    @GetMapping(value = "/export")
    public void download(final Searchable searchable, final Pageable pageable,
            final HttpServletResponse response) {

        final Workbook workbook = this.goodsFileService.export(searchable, pageable);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("货品导出" + LocalDateTime.now() + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            GoodsFileController.log.error("货品导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                GoodsFileController.log.error("货品导出关闭流失败", e);
            }
        }

    }
}
